<script setup  lang="ts">
import type { Key } from 'ant-design-vue/es/_util/type'
import { CloudDownloadOutlined, DeleteOutlined, EyeOutlined, FormOutlined, RedoOutlined } from '@ant-design/icons-vue'
import useClipboard from 'vue-clipboard3'
import ImportTable from './importTable.vue'
import { delTable, genCode, getDataNames, listTable, previewTable, synchDb } from '@/api/tool/gen'
import type { TableQuery, TableVO } from '@/api/tool/gen/types'
import router from '@/router'
import download from '~/plugins/download.ts'

const { toClipboard } = useClipboard()

const route = useRoute()

const tableList = ref<TableVO[]>([])
const loading = ref(true)
const queryFormRef = ref()
const ids = ref<Array<string | number>>([])
const single = ref(true)
const modal = useModal()
const message = useMessage()
const total = ref(0)
const uniqueId = ref('')
const dataNameList = ref<Array<string>>([])

const state = reactive<{
  selectedRowKeys: Key[]
  loading: boolean
}>({
  selectedRowKeys: [], // Check here to configure the default column
  loading: false,
})

const importRef = ref<InstanceType<typeof ImportTable>>()

const queryParams = ref<TableQuery>({
  pageNum: 1,
  pageSize: 10,
  tableName: sessionStorage.getItem('genTableName') || '',
  tableComment: '',
  dataName: '',
})

const preview = ref<any>({
  data: {},
  activeName: 'domain.java',
})
const dialog = reactive<DialogOption>({
  visible: false,
  title: '代码预览',
})

onActivated(() => {
  const time = route.query.t
  if (time != null && time !== uniqueId.value) {
    uniqueId.value = time as string
    queryParams.value.pageNum = Number(route.query.pageNum)
    queryFormRef.value?.resetFields()
    getList()
  }
})

function onSelectChange(selectedRowKeys: Key[]) {
  console.log('selectedRowKeys changed: ', selectedRowKeys)
  state.selectedRowKeys = selectedRowKeys
  single.value = selectedRowKeys.length !== 1
}

/** 查询多数据源名称 */
async function getDataNameList() {
  const res = await getDataNames()
  dataNameList.value = res.data
}

/** 查询表集合 */
async function getList() {
  loading.value = true
  const res = await listTable(queryParams.value)
  console.log(res)
  tableList.value = res.rows
  total.value = res.total
  loading.value = false
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 生成代码操作 */
async function handleGenTable(row?: TableVO) {
  const tbIds = row?.tableId || state.selectedRowKeys
  if (tbIds === '') {
    message.error('请选择要生成的数据')
    return
  }
  if (row?.genType === '1') {
    await genCode(row.tableId)
    message.error(`成功生成到自定义路径：${row.genPath}`)
  }
  else {
    download.zip(`/tool/gen/batchGenCode?tableIdStr=${tbIds}`, 'ruoyi.zip')
  }
}

/** 同步数据库操作 */
async function handleSynchDb(row: TableVO) {
  const tableId = row.tableId
  modal.confirm({
    title: '提示',
    content: `确认要强制同步"${row.tableName}"表结构吗？`,
    onOk: async () => {
      await synchDb(tableId)
      message.success('同步成功')
    },
  })
}

/** 打开导入表弹窗 */
function openImportTable() {
  importRef.value?.show(queryParams.value.dataName)
}

/** 重置按钮操作 */
function resetQuery() {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 预览按钮 */
async function handlePreview(row: TableVO) {
  const res = await previewTable(row.tableId)
  preview.value.data = res.data
  dialog.visible = true
  preview.value.activeName = 'domain.java'
}

/** 修改按钮操作 */
function handleEditTable(row?: TableVO) {
  const tableId = row?.tableId || ids.value[0]
  router.push({ path: `/tool/gen-edit/index/${tableId}`, query: { pageNum: queryParams.value.pageNum } })
}

/** 删除按钮操作 */
async function handleDelete(row?: TableVO) {
  const tableIds = row?.tableId || ids.value
  modal.confirm({
    title: '提示',
    content: `是否确认删除表编号为"${tableIds}"的数据项？`,
    onOk: async () => {
      await delTable(tableIds)
      await getList()
      message.success('删除成功')
    },
  })
}

async function copy(text: string) {
  try {
    await toClipboard(text)
    message.success('复制成功!')
  }
  catch (e) {
    message.error('复制失败!')
  }
}

onMounted(() => {
  getList()
  getDataNameList()
})

onBeforeRouteLeave((to) => {
  if (!to.fullPath.startsWith('/tool/gen-edit'))
    sessionStorage.removeItem('genTableName')
})

function handleTableNameChange(event: any) {
  console.log(event)
  sessionStorage.setItem('genTableName', event || '')
}
</script>

<template>
  <div class="p-2">
    <a-card>
      <template #title>
        <div class="flex-between">
          <div>
            <a-form :model="queryParams" class="inline-form" layout="inline" label-width="68px">
              <a-form-item label="数据源" prop="dataName">
                <a-select
                  v-model:value="queryParams.dataName" filterable allow-clear
                  placeholder="请选择/输入数据源名称" style="width: 200px"
                >
                  <a-select-option key="" label="全部" value="" />
                  <a-select-option v-for="item in dataNameList" :key="item" :label="item" :value="item" />
                </a-select>
              </a-form-item>
              <a-form-item label="表名称" prop="tableName">
                <a-input
                  v-model:value="queryParams.tableName" placeholder="请输入表名称" allow-clear
                  style="width: 200px" @keyup.enter="handleQuery" @change="handleTableNameChange($event.target.value)"
                />
              </a-form-item>
              <a-form-item label="表描述" prop="tableComment">
                <a-input
                  v-model:value="queryParams.tableComment" placeholder="请输入表描述" allow-clear
                  style="width: 200px" @keyup.enter="handleQuery"
                />
              </a-form-item>
              <a-form-item>
                <a-button type="primary" @click="handleQuery">
                  搜索
                </a-button>
                <a-button class="ml-5" @click="resetQuery">
                  重置
                </a-button>
              </a-form-item>
            </a-form>
          </div>
          <div>
            <a-row :gutter="10" class="">
              <a-col>
                <a-button v-hasPermi="['tool:gen:code']" type="primary" @click="handleGenTable()">
                  生成
                </a-button>
              </a-col>
              <a-col>
                <a-button v-hasPermi="['tool:gen:import']" @click="openImportTable">
                  导入
                </a-button>
              </a-col>
            </a-row>
          </div>
        </div>
      </template>

      <a-table
        :loading="loading" :pagination="false" row-key="tableId"
        :row-selection="{ selectedRowKeys: state.selectedRowKeys, onChange: onSelectChange }"
        :data-source="tableList"
      >
        <a-table-column title="序号" type="index" width="50" align="center">
          <template #default="{ index }">
            <span>{{ (queryParams!.pageNum - 1) * queryParams!.pageSize + index + 1 }}</span>
          </template>
        </a-table-column>
        <a-table-column title="数据源" align="center" data-index="dataName" :ellipsis="true" />
        <a-table-column title="表名称" align="center" data-index="tableName" :ellipsis="true" />
        <a-table-column title="表描述" align="center" data-index="tableComment" :ellipsis="true" />
        <a-table-column title="实体" align="center" data-index="className" :ellipsis="true" />
        <a-table-column title="创建时间" align="center" data-index="createTime" width="160" />
        <a-table-column title="更新时间" align="center" data-index="updateTime" width="160" />
        <a-table-column title="操作" align="center" :width="400">
          <template #default="{ record }">
            <a-tooltip content="预览" placement="top">
              <a-button v-hasPermi="['tool:gen:preview']" type="link" @click="handlePreview(record)">
                <EyeOutlined />
              </a-button>
            </a-tooltip>
            <a-tooltip content="编辑" placement="top">
              <a-button v-hasPermi="['tool:gen:edit']" type="link" @click="handleEditTable(record)">
                <FormOutlined />
              </a-button>
            </a-tooltip>
            <a-tooltip content="删除" placement="top">
              <a-button v-hasPermi="['tool:gen:remove']" type="link" @click="handleDelete(record)">
                <DeleteOutlined />
              </a-button>
            </a-tooltip>
            <a-tooltip content="同步" placement="top">
              <a-button v-hasPermi="['tool:gen:edit']" type="link" @click="handleSynchDb(record)">
                <RedoOutlined />
              </a-button>
            </a-tooltip>
            <a-tooltip content="生成代码" placement="top">
              <a-button v-hasPermi="['tool:gen:code']" type="link" @click="handleGenTable(record)">
                <CloudDownloadOutlined />
              </a-button>
            </a-tooltip>
          </template>
        </a-table-column>
      </a-table>
      <div class="text-right mt-5">
        <a-pagination
          v-show="total > 0"
          v-model:current="queryParams.pageNum" v-model:pageSize="queryParams.pageSize" size="small" :total="total"
          show-less-items @change="getList"
        />
      </div>
    </a-card>

    <!-- 预览界面 -->
    <a-modal v-model:open="dialog.visible" :mask-closable="false" :keyboard="false" :title="dialog.title" width="80%" top="5vh" append-to-body class="scrollbar">
      <a-tabs v-model="preview.activeName">
        <a-tab-pane
          v-for="(value, key) in preview.data"
          :key="value"
          :tab="key.toString().substring(key.toString().lastIndexOf('/') + 1, key.toString().indexOf('.vm'))"
        >
          <a-button type="link" class="float-right" @click="copy(value)">
            复制
          </a-button>
          <pre>{{ value }}</pre>
        </a-tab-pane>
      </a-tabs>
    </a-modal>
    <ImportTable ref="importRef" @ok="handleQuery" />
  </div>
</template>
